﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using CommunitySystem.DataService;

namespace CommunitySystem.Ctrls
{
    public partial class DataDictionaryControl : UserControl, INotifyPropertyChanged
    {
        #region PropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string propName)
        {
            if (PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
            }
        }
        #endregion

        public event EventHandler SelectChanged;
        private string _DCode;
        private int _DId;
        private string _DName;

        public double DWidth { get; set; }

        public string DCode { get; set; }
        public int DId { get; set; }
        public string DName { get; set; }

        private string _OldValue;



        public DataDictionaryControl()
        {
            InitializeComponent();
            this.DataContext = this;

            
        }

        
        void DataDictionaryControl_Loaded(object sender, RoutedEventArgs e)
        {
            //if (DictCode != null && DictCode != "")
            this.FindDictItem();


        }

        public bool IsBusy
        {
            get;
            set;
        }
        DataService.DataServiceClient client = new DataService.DataServiceClient();
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            //FindDictItem();

            TextBox1.Width = DWidth;
        }

        //protected override Size ArrangeOverride(Size finalSize)
        //{
        //    return base.ArrangeOverride(finalSize);
        //}
        private void FindDictItem()
        {
            if (!string.IsNullOrEmpty(DictCode))
            {
                Worker.IsBusy = true;

                client.GetDictionaryModelsCompleted += new EventHandler<DataService.GetDictionaryModelsCompletedEventArgs>(client_GetDictionaryModelsCompleted);
                client.GetDictionaryModelsAsync(DictCode);
            }
        }

        void client_GetDictionaryModelsCompleted(object sender, DataService.GetDictionaryModelsCompletedEventArgs e)
        {
            ListModel = new List<DictionaryModel>();
            Worker.IsBusy = false; 
            ListModel = e.Result.ToList();
            BindDataGrid(ListModel);

            if (!string.IsNullOrEmpty(DictCode) && !string.IsNullOrEmpty(ReturnValue))
            {
                //if (DictResultType == DictResultType.ID)
                //{
                if (ListModel != null)
                {
                    DictionaryModel model = new DictionaryModel();
                    if (DictCode == "BZ" || DictCode == "ZJDW" || DictCode == "JHCL")
                    {
                        model = ListModel.SingleOrDefault(t => t.Name == ReturnValue);
                    }
                    else
                    {
                        model = ListModel.SingleOrDefault(t => t.Id == Convert.ToInt32(ReturnValue));
                    }
                    
                    if (model != null)
                    {
                        DId = model.Id;
                        DCode = model.Code;
                        DName = model.Name;
                        ReturnValueID = model.Id.ToString();
                        SetText();
                    }
                }
                //}
            }
        }


        public List<DataService.DictionaryModel> ListModel
        {
            get;
            set;
        }

        private void BindDataGrid(List<DataService.DictionaryModel> dictList)
        {
            if (dictList.Count > 0)
                DataGrid1.ItemsSource = dictList;
        }

        public string DictCode
        {
            get;
            set;
        }

        public string PanDuanIDorName
        {
            get;
            set;
        }

        private string _ChuanRuZhhi;
        public string ChuanRuZhhi
        {
            get { return _ChuanRuZhhi; }
            set
            {
                _ChuanRuZhhi = value; 
                this.OnPropertyChanged("ChuanRuZhhi");
                if (PanDuanIDorName != "ID")
                {
                    client.GetDictionaryModels1Completed += new EventHandler<GetDictionaryModels1CompletedEventArgs>(client_GetDictionaryModels1Completed);
                    client.GetDictionaryModels1Async(ChuanRuZhhi);
                }
                else
                {
                    client.GetDictionaryModelsCompleted +=
                        new EventHandler<DataService.GetDictionaryModelsCompletedEventArgs>(
                            client_GetDictionaryModelsCompleted);
                    client.GetDictionaryModelsAsync(ChuanRuZhhi);
                }
            }
        }

        void client_GetDictionaryModels1Completed(object sender, GetDictionaryModels1CompletedEventArgs e)
        {
            ListModel = new List<DataService.DictionaryModel>();
            Worker.IsBusy = false;
            ListModel = e.Result.ToList();
            BindDataGrid(ListModel);

            if (!string.IsNullOrEmpty(DictCode) && !string.IsNullOrEmpty(ChuanReturnValue))
            {
                //if (DictResultType == DictResultType.ID)
                //{
                if (ListModel != null)
                {
                    var model = ListModel.SingleOrDefault(t => t.Name == ChuanReturnValue);
                    if (model != null)
                    {
                        DId = model.Id;
                        DCode = model.Code;
                        DName = model.Name;
                        ReturnValueID = model.Id.ToString();
                        SetText();
                    }
                }
                //}
            }
        }

        private void TextBox1_GotFocus(object sender, RoutedEventArgs e)
        {
            Button1.Visibility = Visibility.Visible;
            if (!string.IsNullOrEmpty(this.DictCode) && !string.IsNullOrEmpty(this.DCode))
            {
                this._OldValue = this.DCode;
                this.TextBox1.Text = this.DCode;
            }
            this.TextBox1.SelectAll();

            //Button1.Margin = new Thickness(TextBox1.Margin.Right + Button1.Width,2,2.5,202.5);

        }

        private void TextBox1_LostFocus(object sender, RoutedEventArgs e)
        {
            
            Button1.Visibility = Visibility.Collapsed;
            if (string.IsNullOrEmpty(this.DictCode))
            {
                return;
            }
            if (!string.IsNullOrEmpty(this._OldValue) && this._OldValue != this.TextBox1.Text)
            {

                int i = this.TextBox1.Text.IndexOf(']');
                if (i > 0)
                {
                    string tcode = this.TextBox1.Text.Substring(1, i - 1);
                    DictionaryModel item = this.ListModel.SingleOrDefault(t => t.Code == tcode);
                    if (item != null)
                    {
                        this.DId = item.Id;
                        this.DCode = item.Code;
                        this.DName = item.Name;
                        switch (this.DictResultType)
                        {
                            case DictResultType.ID:
                                this.ReturnValue = item.Id.ToString();
                                break;

                            case DictResultType.Code:
                                this.ReturnValue = item.Code;
                                break;

                            case DictResultType.Name:
                                this.ReturnValue = item.Name;
                                break;
                            //case DictResultType.IDandName:
                            //    this.ReturnValue = this.DName.ToString();
                            //    this.ReturnValueID = this.DId.ToString();
                                break;
                        }
                    }
                    else
                    {
                        this.ReturnValue = "";
                        this.DCode = "";
                        this.DName = "";
                        this.DId = 0;
                    }
                }
                else
                {
                    this.ReturnValue = "";
                    this.DCode = "";
                    this.DName = "";
                    this.DId = 0;
                }
            }
            this.SetText();
        }

        private void Button1_Click(object sender, RoutedEventArgs e)
        {
            this.Popup1.IsOpen = true;
            this.TextBox2.Text = "";
            this.TextBox2.Focus();

        }



        private void DataGrid1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.SelectDictItem();
            this.Popup1.IsOpen = false;
        }

        public string ReturnValue
        {
            get;
            set;
        }
        public string ChuanReturnValue
        {
            get;
            set;
        }
        public string ReturnValueID
        {
            get;
            set;
        }

        private void SelectDictItem()
        {
            if (this.DataGrid1.SelectedItem != null)
            {
                DictionaryModel selectedItem = (DictionaryModel)this.DataGrid1.SelectedItem;
                if (selectedItem != null)
                {
                    this.DId = selectedItem.Id;
                    this.DCode = selectedItem.Code;
                    this.DName = selectedItem.Name;
                    switch (this.DictResultType)
                    {
                        case DictResultType.ID:
                            this.ReturnValue = this.DId.ToString();
                            break;

                        case DictResultType.Code:
                            this.ReturnValue = this.DCode.ToString();
                            break;

                        case DictResultType.Name:
                            this.ReturnValue = this.DName.ToString();
                            break;
                        //case DictResultType.IDandName:
                        //    this.ReturnValue = this.DName.ToString();
                        //    this.ReturnValueID = this.DId.ToString();
                        //    break;
                    }
                    this.SetText();
                }
            }
        }

        private void SetText()
        {
            if (!string.IsNullOrEmpty(this.DictCode) && (this.TextBox1 != null))
            {
                switch (this.DictViewType)
                {
                    case DictViewType.ID:
                        this.TextBox1.Text = this.DId.ToString();
                        return;

                    case DictViewType.Code:
                        this.TextBox1.Text = this.DCode;
                        return;

                    case DictViewType.Name:
                        this.TextBox1.Text = this.DName;
                        return;

                    case DictViewType.IDAndName:
                        this.TextBox1.Text = string.IsNullOrEmpty(this.DId.ToString()) ? "" : ("[" + this.DId.ToString() + "]" + this.DName);
                        return;

                    case DictViewType.CodeAndName:
                        this.TextBox1.Text = string.IsNullOrEmpty(this.DCode) ? "" : ("[" + this.DCode + "]" + this.DName);
                        return;

                    default:
                        return;
                }
            }
        }

        public DictViewType DictViewType
        {
            get;
            set;
        }

        public DictResultType DictResultType
        {
            get;
            set;
        }

        private void TextBox2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Up)
            {
                if (this.DataGrid1.SelectedIndex > 0)
                {
                    this.DataGrid1.SelectedIndex--;
                }
                this.DataGrid1.ScrollIntoView(this.DataGrid1.SelectedIndex, 0);
            }
            if (e.Key == Key.Down)
            {
                if ((this.DataGrid1.ItemsSource != null) && ((((List<DictionaryModel>)this.DataGrid1.ItemsSource).Count - 1) > this.DataGrid1.SelectedIndex))
                {
                    this.DataGrid1.SelectedIndex++;
                }
                this.DataGrid1.ScrollIntoView(this.DataGrid1.SelectedIndex, 0);
            }
            if (e.Key == Key.Enter)
            {
                this.SelectDictItem();
                this.Popup1.IsOpen = false;
                this.TextBox1.Focus();
            }
            if (e.Key == Key.Escape)
            {
                this.Popup1.IsOpen = false;
                this.TextBox1.Focus();
            }

        }

        private void GetListModelByCondition(string aa)
        {
            var query = from c in ListModel
                        where c.Code.Contains(aa) || c.Name.Contains(aa)
                        select c;
            this.DataGrid1.ItemsSource = query;

        }

        private void TextBox2_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (this.DataGrid1 != null)
            {
                if (this.TextBox2.Text.Trim() == "")
                {
                    DataGrid1.ItemsSource = ListModel;
                    if (DataGrid1.Rows.Count > 0)
                    {
                        this.DataGrid1.SelectedIndex = 0;
                        this.DataGrid1.ScrollIntoView(0, 0);
                    }
                }
                else
                {
                    GetListModelByCondition(this.TextBox2.Text.Trim());
                    if (DataGrid1.Rows.Count > 0)
                    {
                        this.DataGrid1.SelectedIndex = 0;
                        this.DataGrid1.ScrollIntoView(0, 0);
                    }
                }
            }

        }

        /// <summary>
        /// /
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TextBox1_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (SelectChanged != null)
            {
                SelectChanged(this, EventArgs.Empty);
            }
        }

        private void Popup1_LostFocus(object sender, RoutedEventArgs e)
        {
            string aa = "";
        }

    }

    public enum DictViewType
    {
        ID,
        Code,
        Name,
        IDAndName,
        CodeAndName
    }

    public enum DictResultType
    {
        ID,
        Code,
        Name,
        
    }
}
